﻿using System;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Apache.NMS;
using Apache.NMS.Util;
using Common;
using Microsoft.VisualStudio.TestTools.UITest.Extension;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WidgetApplication;
using WidgetApplication._WGRUS_WidgetTableAdapters;
using InventoryRequestHandler = WidgetApplication.InventoryRequestHandler;

namespace SuppliersUnitTest
{
    [TestClass]
    public class WidgetTest
    {
        #region Setup

        private static InventoryRequestHandler widget;
        private static IConnectionFactory factory;


        [ClassInitializeAttribute]
        public static void ClassInit(TestContext context)
        {
            // NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
            factory = new NMSConnectionFactory(Constants.QUEUE_URI);

            //Load database
            ItemTableAdapter adapter = new ItemTableAdapter();
            _WGRUS_Widget db = new _WGRUS_Widget();
            _WGRUS_Widget.ItemDataTable items = db.Item;

            adapter.Fill(items);

            _WGRUS_Widget.ItemRow i = (from ii in items
                where ii.ItemId == "12"
                select ii).FirstOrDefault();

            _WGRUS_Widget.ItemRow j = (from ii in items
                where ii.ItemId == "54"
                select ii).FirstOrDefault();

            if (i != null)
                i.Delete();

            if (j != null)
                j.Delete();

            adapter.Update(items);


            i = items.NewItemRow();
            i.ItemId = "12";
            i.Desc = "W12";
            i.Price = 123;
            i.StockAmount = 2;
            i.StockLocation = "";

            items.AddItemRow(i);


            j = items.NewItemRow();
            j.ItemId = "54";
            j.Desc = "W54";
            j.Price = 123;
            j.StockAmount = 100;
            j.StockLocation = "Q12-78";

            items.AddItemRow(j);

            adapter.Update(items);


            Tools.QueueCleanup(Constants.WIDGET_INVENTORY_REQUEST_QUEUE);
            Tools.QueueCleanup(Constants.WIDGET_INVENTORY_RESPONSE_QUEUE);
            Tools.QueueCleanup(Constants.WIDGET_CATALOG_QUEUE);

            WidgetApplication.Program.Init();
        }

        [ClassCleanupAttribute]
        public static void ClassCleanup()
        {
            WidgetApplication.Program.Stop();
        }

        [TestInitialize]
        public void TestSetup()
        {
        }

        [TestCleanup()]
        public void Cleanup()
        {
            //Cleanup Queues
            using (IConnection connection = factory.CreateConnection())
            using (ISession session = connection.CreateSession())
            {
                IDestination destination = SessionUtil.GetDestination(session,
                    Constants.WIDGET_INVENTORY_REQUEST_QUEUE);
                // Create a consumer
                using (IMessageConsumer consumer = session.CreateConsumer(destination))
                {
                    connection.Start();
                    do
                    {
                    } while (consumer.Receive(new TimeSpan(0, 0, 0, 1)) != null);
                }
            }
        }

        #endregion

        //WidgetRequest
        //WidgetRequestBadFormat
        //WidgetRequestOutOfStock
        //WidgetRequestUnKnownItem

        #region Widget Application

        [TestMethod]
        public void TestMessageReceived()
        {
            //Setup
            string req = Tools.GetTestXml("WidgetRequest");

            //Execute
            Tools.QueueSend(Constants.WIDGET_INVENTORY_REQUEST_QUEUE, req);
            //Test
            IMessage message = Tools.GetQueueMessage(Constants.WIDGET_INVENTORY_RESPONSE_QUEUE);
            Assert.IsNotNull(message);
            var m = message as ITextMessage;
            Assert.IsNotNull(m);
            string strXml = m.Text;
            Assert.IsFalse(string.IsNullOrEmpty(strXml));
            XDocument doc = Tools.LoadMyXml(strXml);
            Assert.IsNotNull(doc);
            Assert.IsNotNull(doc);
            //Linq to xml
            // Do a simple query and print the results to the console
            XNamespace ns = "http://widget.com/WGRUS";

            var d = (from item in doc.Descendants(ns + "InventoryRes")
                select new
                {
                    id = item.Element("ItemId").Value,
                    result = item.Element("InStock").Value
                }).First();

            Assert.AreEqual("12", d.id);
            Assert.AreEqual(d.result, "true");
        }

        [TestMethod]
        public void TestMessageReceivedOutOfStock()
        {
            //Setup
            string req = Tools.GetTestXml("WidgetRequestOutOfStock");

            //Execute
            Tools.QueueSend(Constants.WIDGET_INVENTORY_REQUEST_QUEUE, req);
            //Test
            IMessage message = Tools.GetQueueMessage(Constants.WIDGET_INVENTORY_RESPONSE_QUEUE);
            Assert.IsNotNull(message);
            var m = message as ITextMessage;
            Assert.IsNotNull(m);
            string strXml = m.Text;
            Assert.IsFalse(string.IsNullOrEmpty(strXml));
            XDocument doc = Tools.LoadMyXml(strXml);
            Assert.IsNotNull(doc);
            Assert.IsNotNull(doc);
            //Linq to xml
            // Do a simple query and print the results to the console
            XNamespace ns = "http://widget.com/WGRUS";

            var d = (from item in doc.Descendants(ns + "InventoryRes")
                     select new
                     {
                         id = item.Element("ItemId").Value,
                         result = item.Element("InStock").Value
                     }).First();

            Assert.AreEqual("12", d.id);
            Assert.AreEqual(d.result, "false");
        }

        [TestMethod]
        public void TestMessageReceivedUnKnownItem()
        {
            //Setup
            string req = Tools.GetTestXml("WidgetRequestUnKnownItem");

            //Execute
            Tools.QueueSend(Constants.WIDGET_INVENTORY_REQUEST_QUEUE, req);
            //Test
            IMessage message = Tools.GetQueueMessage(Constants.WIDGET_INVENTORY_RESPONSE_QUEUE);
            Assert.IsNotNull(message);
            var m = message as ITextMessage;
            Assert.IsNotNull(m);
            string strXml = m.Text;
            Assert.IsFalse(string.IsNullOrEmpty(strXml));
            XDocument doc = Tools.LoadMyXml(strXml);
            Assert.IsNotNull(doc);
            Assert.IsNotNull(doc);
            //Linq to xml
            // Do a simple query and print the results to the console
            XNamespace ns = "http://widget.com/WGRUS";

            var d = (from item in doc.Descendants(ns + "InventoryRes")
                     select new
                     {
                         id = item.Element("ItemId").Value,
                         result = item.Element("InStock").Value
                     }).First();

            Assert.AreEqual("1111", d.id);
            Assert.AreEqual(d.result, "false");
        }

        [TestMethod]
        public void TestMessageReceivedBadFormat()
        {
            //Setup
            string req = Tools.GetTestXml("WidgetRequestBadFormat");

            //Execute
            Tools.QueueSend(Constants.WIDGET_INVENTORY_REQUEST_QUEUE, req);
            //Test
            IMessage message = Tools.GetQueueMessage(Constants.WIDGET_INVENTORY_RESPONSE_QUEUE);
            Assert.IsNotNull(message);
            var m = message as ITextMessage;
            Assert.IsNotNull(m);
            string strXml = m.Text;
            Assert.IsFalse(string.IsNullOrEmpty(strXml));
            XDocument doc = Tools.LoadMyXml(strXml);
            Assert.IsNotNull(doc);
            Assert.IsNotNull(doc);
            //Linq to xml
            // Do a simple query and print the results to the console
            XNamespace ns = "http://widget.com/WGRUS";

            var d = (from item in doc.Descendants(ns + "InventoryRes")
                     select new
                     {
                         id = item.Element("ItemId").Value,
                         result = item.Element("InStock").Value
                     }).First();

            Assert.AreEqual("-1", d.id);
            Assert.AreEqual(d.result, "false");
        }


        [TestMethod]
        public void TestSendCatalog()
        {
            //Setup

            //Execute

            //Test
        }

        #endregion
    }
}